#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from common.common import exter_attack
from common.const import SysData
from exchange import log
from exchange.backup.backup_base.base_exchange_backup_gen_sub_job import ExchangeBackupBackupGenSubJob
from exchange.commons.common import output_result_file
from exchange.commons.const import ExchangeJobInfo, SubJobPolicy, ExchangeBackupSubJobName, \
    SubJobPriorityEnum, JobBackupType
from exchange.commons.exchange_exception import ExchangeErrCodeException
from exchange.commons.exchange_function_tool import log_start_end


class DagBackupGenSubJob(ExchangeBackupBackupGenSubJob):
    def __init__(self, pid):
        super().__init__(pid)
        self._pid = pid

    @log_start_end()
    def do_gen_sub_job_task(self, job_info: ExchangeJobInfo):
        log.info("backup_gen_sub_job start!")
        nodes = self._param.get("job").get("protectEnv").get("nodes")
        response = []
        for node in nodes:
            node_id = node['id']
            job_policy = SubJobPolicy.FIXED_NODE.value
            job_name = ExchangeBackupSubJobName.SUB_EXEC
            job_priority = SubJobPriorityEnum.JOB_PRIORITY_1.value
            response.append(self.build_sub_job(job_priority, job_policy, job_name, node_id, job_info))

        # 第二个子任务，上报备份时间
        log.info("Gen sub job upload log copy sub job")
        node_id = self._param.get("job").get("protectEnv").get("nodes")[0].get("id", "")
        job_policy1 = SubJobPolicy.LOCAL_NODE.value
        job_name = ExchangeBackupSubJobName.SUB_UPLOAD
        job_priority = SubJobPriorityEnum.JOB_PRIORITY_2.value
        response.append(self.build_sub_job(job_priority, job_policy1, job_name, node_id, job_info))
        log.info(f"Gen sub job result:{response}")
        output_result_file(job_info.pid, response)
        return True


@exter_attack
def do_exec(pid):
    try:
        job = DagBackupGenSubJob(pid)
        job.do_gen_sub_job_task(job.get_job_info())
    except ExchangeErrCodeException as err_str:
        log.error(f"Post backup failed, err: {err_str}, pid:{pid}")
        return False
    return True

if __name__ == '__main__':
    for line in sys.stdin:
        SysData.SYS_STDIN = line
        break

    if len(sys.argv) < 1:
        log.error("Param is wrong.")
        sys.exit(1)
    pid_args2 = sys.argv[1]
    try:
        do_exec(pid_args2)
    except Exception as err:
        log.error(f"Err: {err}, pid: {pid_args2}")
        sys.exit(0)

    sys.exit(0)